import {
    existplayer,
    Write_player,
    Write_equipment,
    isNotNull,
    player_efficiency,
    get_random_fromARR,
    Read_player,
    Read_equipment,
    Add_HP,
    exist_najie_thing,
    Add_修为,
    Add_血气,
    Add_najie_thing,
    Add_灵石,
    LevelTask,
    get_log_img,
    channel
  } from '../../model/xiuxian.js';
  import { plugin, verc, data, config } from '../../api/api.js';
  import { monsterscache, add } from '../fight/moster.js';
  import { monsterbattle } from '../fight/battle.js';
 

export class findkill extends plugin {
    constructor() {
      super({
        name: 'Userkill',
        dsc: 'zd模块',
        event: 'message',
        rule: [
          {
            reg: '^探索怪物$',
            fnc: 'Exploremonsters',
          },
          {
            reg: '^击杀.*$',
            fnc: 'Kill',
          },
          
        ],
      });
    }
    async Exploremonsters(e) {
        let usr_qq = e.user_id;
        let player = await Read_player(usr_qq);
        //有无账号
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) return false;

        const position = data.position_list.find((item)=> 
            player.x >= parseInt(item.x1) && player.x <= parseInt(item.x2) &&
            player.y >= parseInt(item.y1) && player.y <= parseInt(item.y2)
        );
        if (!position) {
            e.reply("当前位置无效，无法探索怪物。");
            return;
        }
        const weizhiID = position.id.split('-');
        const i = weizhiID[1]; // 怪物分布区域
        const location = position.name; // 获取位置名称

        const msg = [];
        const monster = await monsterscache({ i, location }); // 传递 location 参数
        for (let item of monster) {
            msg.push("\n" + item.id + " [" + item.name + "] 等级:" + item.level); // 调整编号和怪物名格式
        }
        e.reply(msg);
        return;
    }

    async Kill(e) {
        let usr_qq = e.user_id;
        let player = await Read_player(usr_qq);

        // 检查玩家是否存在
        if (!await existplayer(usr_qq)) {
            e.reply("你尚未创建角色，请先创建角色！");
            return false;
        }

        // 检查CD时间
        let last_kill = await redis.get('xiuxian:player:' + usr_qq + ':last_kill');
        last_kill = parseInt(last_kill);
        let CDTime = 1; // CD时间（分钟）
        const now_time = new Date().getTime();
        let transferTimeout = parseInt(60000 * CDTime);
        if (now_time < last_kill + transferTimeout) {
            let game_m = Math.trunc((last_kill + transferTimeout - now_time) / 60 / 1000);
            let game_s = Math.trunc(((last_kill + transferTimeout - now_time) % 60000) / 1000);
            e.reply(
                `每${transferTimeout / 1000 / 60}分钟一次。` +
                `cd: ${game_m}分${game_s}秒`
            );
            // 存在CD，直接返回
            return false;
        }

        // 检查玩家是否正在进行其他动作
        let action = await redis.get('xiuxian:player:' + usr_qq + ':action');
        if (action) {
            e.reply('你正在进行其他活动，无法战斗！');
            return;
        }

        // 获取当前位置的怪物列表
        const position = data.position_list.find((item)=> 
            player.x >= parseInt(item.x1) && player.x <= parseInt(item.x2) &&
            player.y >= parseInt(item.y1) && player.y <= parseInt(item.y2)
        );
        if (!position) {
            e.reply("当前位置无效，无法击杀怪物。");
            return;
        }
        const weizhiID = position.id.split('-');
        const i = weizhiID[1];
        const location = position.name;
        const monsters = await monsterscache({ i, location });

        // 提取怪物编号
        const monsterId = parseInt(e.msg.replace(/^击杀/, '').trim());
        if (isNaN(monsterId) || monsterId < 1 || monsterId > monsters.length) {
            e.reply("无效的怪物编号，请检查后重试！");
            return;
        }

        // 获取目标怪物
        const targetMonster = monsters[monsterId - 1];

        // 生成怪物属性
        const { attributes: monsterAttributes, mutationMsg, multiplier } = await generateMonsterAttributes(targetMonster, i);

        // 模拟战斗逻辑
        const battleResult = await monsterbattle({
            UserA: {
                名号: player.名号,
                当前血量: player.当前血量,
                攻击: player.攻击,
                防御: player.防御,
                暴击率: player.暴击率,
                暴击伤害: player.暴击伤害,
                速度: player.速度,
                uid: usr_qq
            },
            UserB: monsterAttributes
        });

        // 更新玩家状态
        player.当前血量 = battleResult.当前血量.a;
        await Write_player(usr_qq, player);

        // 分两条消息发送战斗过程和结果
        const processMsg = mutationMsg ? `${mutationMsg}\n${battleResult.processMsg.join('')}` : battleResult.processMsg.join('');
        e.reply(processMsg); // 发送战斗过程
        if (battleResult.victory === usr_qq) {
            const rewardMsg = await rewardPlayer(usr_qq, targetMonster.level, multiplier); // 获取奖励消息
            e.reply(`战斗胜利！${battleResult.resultMsg}\n${rewardMsg}`); // 合并战斗结果和奖励消息
        } else if (battleResult.victory === null) {
            e.reply(`战斗平手！${battleResult.resultMsg}`); // 平手时仅发送结果消息，无奖励
        } else {
            e.reply(`战斗失败！${battleResult.resultMsg}`);
        }

        // 更新CD时间
        await redis.set('xiuxian:player:' + usr_qq + ':last_kill', now_time);

        return;
    }
}

// 生成怪物属性
async function generateMonsterAttributes(monster, regionId) {
    const isMutated = await handleMutation(regionId);
    const multiplier = isMutated ? Math.floor(Math.random() * (5 - 2)) + 2 : 1; // 变强倍数
    const levelData = data.Level_list.find((item) => item.level_id === monster.level + 1);

    const mutationMsg = isMutated
        ? `注意！怪物[${monster.name}]发生了变异，属性提升了${multiplier}倍！`
        : null;

    return {
        attributes: {
            名号: monster.name,
            当前血量: levelData.基础血量 * multiplier,
            攻击: levelData.基础攻击 * multiplier,
            防御: levelData.基础防御 * multiplier,
            血量上限: levelData.基础血量 * multiplier,
            暴击率: levelData.基础暴击 * multiplier,
            暴击伤害: 1.5,
            速度: levelData.level_id + multiplier
        },
        mutationMsg,
        multiplier
    };
}

// 处理怪物变异逻辑
async function handleMutation(regionId) {
    const mutationChance = 0.15; // 固定变异概率为 15%
    const isMutated = Math.random() < mutationChance;
    if (isMutated) {
        await add({ i: regionId, num: 1 }); // 更新变异计数
    }
    return isMutated; // 返回是否变异
}

// 奖励玩家
async function rewardPlayer(playerId, monsterLevel, multiplier) {
    // 奖励修为
    const expReward = monsterLevel * 150 * multiplier; // 奖励修为随变异倍数翻倍
    await Add_修为(playerId, expReward);

    // 奖励血气
    const bloodReward = monsterLevel * 200 * multiplier; // 奖励血气随变异倍数翻倍
    await Add_血气(playerId, bloodReward);

    // 奖励灵石
    const stoneReward = monsterLevel * 200 * multiplier; // 奖励灵石随变异倍数翻倍
    await Add_灵石(playerId, stoneReward);

    // 奖励物品
    // 生成0-100之间的随机数
const m = Math.floor(Math.random() * 101);
console.log(`随机数 m 的值为: ${m}`);
let itemDropList = data.diaoluo_list; // 确保正确获取掉落列表
    const dropRates = determineDropLevel(monsterLevel); // 获取掉落概率
    const randomItems = [];

    if (m <= dropRates.one) {
        const lowLevelItems = itemDropList.one; // 获取低级物品列表
        if (lowLevelItems.length > 0) {
            randomItems.push(get_random_fromARR(lowLevelItems));
        }
    }
    if (m <= dropRates.two) {
        const midLevelItems = itemDropList.two; // 获取中级物品列表
        if (midLevelItems.length > 0) {
            randomItems.push(get_random_fromARR(midLevelItems));
        }
    }
    if (m <= dropRates.three) {
        const highLevelItems = itemDropList.three; // 获取高级物品列表
        if (highLevelItems.length > 0) {
            randomItems.push(get_random_fromARR(highLevelItems));
        }
    }
    if (m <= dropRates.fuor) {
        const rareItems = itemDropList.fuor; // 获取稀有物品列表
        if (rareItems.length > 0) {
            randomItems.push(get_random_fromARR(rareItems));
        }
    }
    let num = 1;

    // 添加物品到玩家背包
    for (const item of randomItems) {
        if (item) {
            await Add_najie_thing(playerId, item.name, item.class, num);
        }
    }

    // 奖励消息
    let rewardMsg = `你获得了以下奖励：\n`;
    rewardMsg += `[修为]：${expReward}\n`;
    rewardMsg += `[血气]：${bloodReward}\n`;
    rewardMsg += `[灵石]：${stoneReward}\n`;

    if (randomItems.length > 0) {
        rewardMsg += `[物品]：${randomItems.map(item => `${item.name} *${num}`).join(', ')}\n`; // 修复数量显示
    } else {
        rewardMsg += `[物品]：无\n`; // 如果没有物品掉落，明确提示
    }

    // 根据倍数说明奖励情况
    if (multiplier > 1) {
        rewardMsg += `（由于怪物变异，奖励翻倍倍数为：${multiplier}）`;
    }

    return rewardMsg; // 返回奖励消息
}

// 确定掉落概率
function determineDropLevel(monsterLevel) {
    return {
        one: Math.max(50, 50 + monsterLevel / 2), // 修正概率计算，确保低级物品概率合理
        two: Math.max(25, 25 + monsterLevel / 4), // 确保中级物品概率不会超过上限
        three: Math.max(8, 8 + monsterLevel / 6), // 确保高级物品概率不会超过上限
        fuor: Math.max(3, 3 + monsterLevel / 10)  // 确保稀有物品概率不会超过上限
    };
}



